# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import random

from scrapy import signals
import requests
import logging

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class JdskuspiderSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class JdskuspiderDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class ProxyMiddleWare:

    logger = logging.getLogger(__name__)
    proxy = ''

    def get_random_proxy(self, spider):
        """
        从代理页面获取代理url
        :return: 代理url
        """
        try:
            response = requests.get(spider.settings.get('PROXY_SERVER_URL'))
            if response.status_code == 200:
                # 得到类似['125.111.146.122:4345', '114.239.146.151:4356', '']
                url_list = response.text.split("\r\n")
                # 去掉最后一个空字符串
                url_list.pop(-1)

                proxy = '{}'.format(random.choice(url_list))
                ip = {"http": "http://" + proxy}
                logging.info("=====获取代理: {}=====".format(ip))

                r = requests.get("http://www.baidu.com", proxies=ip, timeout=10)
                if r.status_code == 200:
                    logging.info("=====代理通过测试, 选择该ip: {}=====".format(ip))
                    return proxy
        except:
            logging.info('=====未通过代理测试, 重新从代理商处获取代理=====')
            return self.get_random_proxy(spider)

    def get_proxy(self, spider):
        """
        从代理池里获取代理, 节省代理个数
        :return: proxy, 形式为: '125.111.146.122:4345'
        """
        if self.proxy == "":
            self.proxy = self.get_random_proxy(spider)
        else:
            ip = {"http": "http://" + str(self.proxy)}
            r = requests.get(spider.settings.get("TEST_PAGE"), proxies=ip, timeout=10)
            if r.status_code == 200:
                #'window.location.href'等等...字段是封ip页面开头有的元素
                if not "window.location.href" in r.text[0:50]:
                    logging.info("=====代理通过测试, 继续使用该ip: {}=====".format(self.proxy))
                else:
                    self.proxy = self.get_random_proxy(spider)
            else:
                self.proxy = self.get_random_proxy(spider)
            return self.proxy

    def process_request(self, request, spider):
        """
        scrapy.middlewares模板的方法
        使用代理对要爬取的网页request
        """
        proxy = self.get_proxy(spider)
        if proxy:
            self.logger.debug('======' + '使用代理 ' + str(proxy) + "======")
            request.meta['proxy'] = 'https://{proxy}'.format(proxy=proxy)

    def process_response(self, request, response, spider):
        """
        scrapy.middlewares模板的方法
        使用代理对要爬取的网页request失败时, 重新使用代理爬取
        """
        if response.status != 200:
            self.logger.info("=====使用代理ip request网页获得失败response, 重新获取代理ip=====")
            request.meta['proxy'] = 'https://{proxy}'.format(proxy=self.get_random_proxy(spider))
            return request
        return response